/**
 * IdleConnectionMonitorThread.java<br>
 * 
 * @author aaronwong.sd@foxmail.com
 * @version 下午3:07:10
 */
package com.iwechat.httpClient;

import java.util.concurrent.TimeUnit;

import org.apache.http.conn.HttpClientConnectionManager;

import com.iwechat.PropertyUtils;

/**
 * 超时链接管理
 * 
 * @author aaronwong.sd@foxmail.com
 */
public class IdleConnectionMonitorThread extends Thread {

    private final HttpClientConnectionManager connMgr;
    private volatile boolean                  shutdown;
    private int                               idleTime;

    public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
        this.connMgr = connMgr;
        PropertyUtils util = PropertyUtils.getInstance();
        idleTime = util.getIntValue("settings", "connection.idle.time");
        if (idleTime < 30) {
            idleTime = 30;
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        try {
            while (!shutdown) {
                synchronized (this) {
                    wait(5000);
                    // 关闭失效的连接
                    connMgr.closeExpiredConnections();
                    // 可选的, 关闭idleTime秒内不活动的连接
                    connMgr.closeIdleConnections(idleTime, TimeUnit.SECONDS);
                }
            }
        } catch (InterruptedException ex) {
            // terminate
        }
    }

    public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
        }
    }
}
